package com.yizhuoyan.his.webapi.controller;

import com.yizhuoyan.his.dto.JSONResponse;
import com.yizhuoyan.his.dto.SysAccountAuthorizationResult;
import com.yizhuoyan.his.service.SysAccountAuthenticationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@RestController
@Slf4j
public class SysAccountAuthenticationController {

    @Autowired
    SysAccountAuthenticationService authenticationService;

    @PostMapping("/api/session")
    public JSONResponse login(String account, String password, HttpServletRequest req)throws Exception{
        log.debug("{}登录,判断是否重复登录",account);
        HttpSession session = req.getSession(false);
        log.trace("从request中获取之前创建的session");
        if(session==null){
            log.debug("{}是第一次登录",account);
            session=req.getSession(true);
        }else {
            Object authorizationResult = session.getAttribute(session.getId());
            if (authorizationResult != null) {
                log.debug("{}重复登录，销毁之前",account);
                session.invalidate();
                session=req.getSession(true);
            }
        }
        SysAccountAuthorizationResult result = authenticationService.login(account, password);
        log.debug("{}登录成功，保存授权信息到session中",account);
        //session.setAttribute(SysAccountAuthorizationResult.class.getSimpleName(),result);
        session.setAttribute(session.getId(),result);
        return JSONResponse.ok();
    }
    @GetMapping("/api/session")
    public JSONResponse getSession(HttpSession session)throws Exception{
        SysAccountAuthorizationResult result =
                (SysAccountAuthorizationResult) session.getAttribute(session.getId());
        if(result==null){
            return JSONResponse.fail("should never happen!");
        }
        return JSONResponse.ok(result);
    }
    @DeleteMapping("/api/session")
    public JSONResponse deleteSession(HttpSession session)throws Exception{

        SysAccountAuthorizationResult result =
                (SysAccountAuthorizationResult) session.getAttribute(session.getId());
        if(result==null){
            return JSONResponse.fail("should never happen!");
        }else{
            log.debug("{}注销",result.getAccount());
        }

        return JSONResponse.ok(result);
    }
}
